package com.hardroid.workload.ui.tablet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

import com.hardroid.workload.R;
import com.hardroid.workload.ui.AboutActivity;
import com.hardroid.workload.ui.HelpActivity;
import com.hardroid.workload.ui.QuestionaireActivity;
import com.hardroid.workload.ui.ResultActivity;
import com.hardroid.workload.ui.SheetActivity;
import com.hardroid.workload.ui.UnitKerjaActivity;
import com.hardroid.workload.utils.HardroidUtils;
import com.hardroid.workload.utils.Singleton;
import com.hardroid.workload.workcalc.Employer;
import com.hardroid.workload.workcalc.ObsvProject.ProjectStatus;
import com.hardroid.workload.workcalc.WorkUnit;

public class DashboardMultiPaneActivity extends Activity {

	public int m1, h1, m2, h2;

	public static final int TIME_PICKER_START_DIALOG = 4;
	public static final int TIME_PICKER_END_DIALOG = 5;

	public static final int DIALOG_RESPONDEN_NOT_ENOUGH = 0;
	public static final int DIALOG_CONFIRMATION_FINISH = 1;

	public final static int EXIT_DIALOG = 3;

	private Button beginObsvButton;
	private Button finishObsvButton;
	private Button fillQuestEmployerButton;
	private Button fillQuestAtasanButton;

	private AlertDialog warningDialog;
	private AlertDialog exitDialog;
	private AlertDialog.Builder warningBuilder;
	private AlertDialog confirmationDialog;

	private String warningMessage;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tablet_dashboard);

		fillQuestAtasanButton = (Button) findViewById(R.id.tablet_dashboard_fill_questionaire_atasan);
		fillQuestAtasanButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!Singleton.currentProject.lEmployer.isEmpty()) {
					Intent i = new Intent(getBaseContext(),
							UnitKerjaActivity.class);
					// i.putExtra("id", 0);
					startActivity(i);
				} else {
					Toast.makeText(getBaseContext(), "Tidak ada responden",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		fillQuestEmployerButton = (Button) findViewById(R.id.tablet_dashboard_fill_questionaire);
		fillQuestEmployerButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!Singleton.currentProject.lEmployer.isEmpty()) {
					Intent i = new Intent(getBaseContext(),
							QuestionaireActivity.class);
					i.putExtra("id", 0);
					startActivity(i);
				} else {
					Toast.makeText(getBaseContext(), "Tidak ada responden",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		beginObsvButton = (Button) findViewById(R.id.tablet_dashboard_begin_observation);
		beginObsvButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				if (!Singleton.currentProject.lEmployer.isEmpty()) {

					if (Singleton.isDayReferenceValid()) {
						Intent i = new Intent(getBaseContext(),
								SheetActivity.class);
						i.putExtra("id", 0);
						startActivity(i);
					} else {
						showDialog(TIME_PICKER_START_DIALOG);
					}

				} else {
					Toast.makeText(getBaseContext(), "Tidak ada responden",
							Toast.LENGTH_SHORT).show();
				}
			}
		});

		// enable/disable begin obsv button
		// if (Singleton.currentProject.projectStatus ==
		// ProjectStatus.PROJECT_FINISHED) {
		// beginObsvButton.setEnabled(false);
		//
		// } else {
		// beginObsvButton.setEnabled(true);
		// }

		finishObsvButton = (Button) findViewById(R.id.tablet_dashboard_finish_observation);

		// mengganti tulisan si finish Obsv Button
		if (Singleton.currentProject != null) {
			if (Singleton.currentProject.projectStatus == ProjectStatus.PROJECT_FINISHED) {
				finishObsvButton.setText("Lihat Hasil");
			}
		} else {
			Log.e("ERRORR", "NULL");
		}

		finishObsvButton.setOnClickListener(new View.OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				// if (Singleton.currentProject.projectStatus ==
				// ProjectStatus.PROJECT_FINISHED) {
				// // kalo uda finished statusnya, digenerate lah resultnya
				// for (Employer e : Singleton.currentProject.lEmployer) {
				// e.result.generateResult();
				// }
				// startActivity(new Intent(getApplicationContext(),
				// ResultActivity.class));
				// } else {
				// // kalo belum finished statusnya
				// if (!Singleton.currentProject.lEmployer.isEmpty()) {
				// List<Integer> list = Singleton.currentProject
				// .getEmployerDataNotEnough();
				// if (list.isEmpty()) {
				// showDialog(DIALOG_CONFIRMATION_FINISH);
				// } else {
				// warningBuilder = new AlertDialog.Builder(
				// getContext());
				// warningBuilder
				// .setTitle("Warning")
				// .setCancelable(true)
				// .setPositiveButton(
				// "OK",
				// new DialogInterface.OnClickListener() {
				//
				// @Override
				// public void onClick(
				// DialogInterface dialog,
				// int which) {
				//
				// }
				// });
				// warningBuilder.setMessage(""); // CODE IMBA
				// warningDialog = warningBuilder.create();
				//
				// StringBuilder b = new StringBuilder("Employer ");
				//
				// for (Integer i : list) {
				// Log.i("List Not enough ", i + " added");
				// b.append((i+1)).append(',');
				// }
				//
				// b.deleteCharAt(b.lastIndexOf(","));
				// b.append(" data haven't yet completed");
				//
				// Log.i("Dashboard", "Warning : " + b.toString());
				// warningMessage = b.toString();
				//
				// warningDialog.setMessage(warningMessage);
				//
				// showDialog(DIALOG_RESPONDEN_NOT_ENOUGH);
				// }
				// } else {
				// // list observasinya masih kosong, ga ada yang bisa dilihat
				// Toast.makeText(getApplicationContext(),
				// "No Observation", Toast.LENGTH_SHORT).show();
				// }
				// }

				if (Singleton.currentProject.projectStatus == ProjectStatus.PROJECT_FINISHED) {
					// kalo uda finished statusnya, digenerate lah resultnya

					if (!Singleton.currentProject.lEmployer.isEmpty()) {
						List<Integer> list = Singleton.currentProject
								.getEmployerDataNotEnough();
						if (list.isEmpty()) {
							for (Employer e : Singleton.currentProject.lEmployer) {
								e.result.generateResult();
							}

							// generate result for work unit
							List<WorkUnit> lWorkU = Singleton.currentProject.lWorkUnit;
							if (!lWorkU.isEmpty()) {
								for (WorkUnit w : lWorkU) {
									w.generateResultForEmployers();
								}
							}

							startActivity(new Intent(getApplicationContext(),
									ResultActivity.class));
						} else {
							warningBuilder = new AlertDialog.Builder(
									getContext());
							warningBuilder
									.setTitle("Warning")
									.setCancelable(true)
									.setPositiveButton(
											"OK",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {

												}
											});
							warningBuilder.setMessage(""); // CODE IMBA
							warningDialog = warningBuilder.create();

							StringBuilder b = new StringBuilder(
									"Data responden ");

							for (Integer i : list) {
								Log.i("List Not enough ", i + " added");
								b.append((i + 1)).append(',');
							}

							b.deleteCharAt(b.lastIndexOf(","));
							b.append(" belum lengkap diisi");

							Log.i("Dashboard", "Warning : " + b.toString());
							warningMessage = b.toString();

							warningDialog.setMessage(warningMessage);

							showDialog(DIALOG_RESPONDEN_NOT_ENOUGH);
						}
					} else {
						// list observasinya masih kosong, ga ada yang bisa
						// dilihat
						Toast.makeText(getApplicationContext(),
								"Tidak ada observasi", Toast.LENGTH_SHORT)
								.show();
					}

				} else {
					// kalo belum finished statusnya
					if (!Singleton.currentProject.lEmployer.isEmpty()) {
						List<Integer> list = Singleton.currentProject
								.getEmployerDataNotEnough();
						if (list.isEmpty()) {
							showDialog(DIALOG_CONFIRMATION_FINISH);
						} else {
							warningBuilder = new AlertDialog.Builder(
									getContext());
							warningBuilder
									.setTitle("Warning")
									.setCancelable(true)
									.setPositiveButton(
											"OK",
											new DialogInterface.OnClickListener() {

												@Override
												public void onClick(
														DialogInterface dialog,
														int which) {

												}
											});
							warningBuilder.setMessage(""); // CODE IMBA
							warningDialog = warningBuilder.create();

							StringBuilder b = new StringBuilder(
									"Data responden ");

							for (Integer i : list) {
								Log.i("List Not enough ", i + " added");
								b.append((i + 1)).append(',');
							}

							b.deleteCharAt(b.lastIndexOf(","));
							b.append(" belum lengkap diisi");

							Log.i("Dashboard", "Warning : " + b.toString());
							warningMessage = b.toString();

							warningDialog.setMessage(warningMessage);

							showDialog(DIALOG_RESPONDEN_NOT_ENOUGH);
						}
					} else {
						// list observasinya masih kosong, ga ada yang bisa
						// dilihat
						Toast.makeText(getApplicationContext(),
								"Tidak ada observasi", Toast.LENGTH_SHORT)
								.show();
					}
				}

			}
		});

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setMessage("Anda yakin ingin keluar?")
				.setCancelable(true)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								Singleton.saveProject(Singleton.currentProject);
								finish();
								System.exit(0);
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

		exitDialog = builder.create();

		AlertDialog.Builder confBuilder = new AlertDialog.Builder(getContext());
		confBuilder.setTitle("Warning!!!");
		confBuilder
				.setMessage(
						"Anda yakin ingin menyelesaikan observasi? Anda tidak akan dapat menambah karyawan lagi setelah mengklik tombol ini")
				.setCancelable(true)
				.setPositiveButton("Yes",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub
								for (Employer e : Singleton.currentProject.lEmployer) {
									e.result.generateResult();
								}
								Singleton.currentProject.projectStatus = ProjectStatus.PROJECT_FINISHED;
								Singleton.saveProject(Singleton.currentProject);
								if (Singleton.currentProject.projectStatus == ProjectStatus.PROJECT_FINISHED) {
									beginObsvButton.setEnabled(false);
								} else {
									beginObsvButton.setEnabled(true);
								}
								if (Singleton.currentProject.projectStatus == ProjectStatus.PROJECT_FINISHED) {
									finishObsvButton.setText("Lihat Hasil");
								}
								startActivity(new Intent(
										getApplicationContext(),
										ResultActivity.class));
							}
						})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub
						dialog.cancel();
					}
				});

		confirmationDialog = confBuilder.create();
	}

	@Override
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_RESPONDEN_NOT_ENOUGH: {
			((AlertDialog) dialog).setMessage(warningMessage);
		}
		}
	}

	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_RESPONDEN_NOT_ENOUGH: {

			return warningDialog;
		}
		case EXIT_DIALOG: {
			return exitDialog;
		}
		case DIALOG_CONFIRMATION_FINISH: {
			return confirmationDialog;
		}
		case TIME_PICKER_START_DIALOG: {
			Dialog dialog;
			dialog = new TimePickerDialog(this, mTimeSetListener, 8, 0, true);
			dialog.setTitle("Mulai kerja");
			return dialog;

		}
		case TIME_PICKER_END_DIALOG: {
			Dialog dialog;
			dialog = new TimePickerDialog(this, mTimeSetListener2, 17, 0, true);
			dialog.setTitle("Kerja berakhir");
			return dialog;
		}

		}

		return super.onCreateDialog(id);
	}

	@Override
	public void onBackPressed() {
		// TODO Auto-generated method stub
		showDialog(EXIT_DIALOG);
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// if
		// (Singleton.currentProject.projectStatus==ProjectStatus.PROJECT_FINISHED){
		// beginObsvButton.setEnabled(false);
		// }else{
		// beginObsvButton.setEnabled(true);
		// }
	}

	public Context getContext() {
		return this;
	}

	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			h1 = hourOfDay;
			m1 = minute;
			showDialog(TIME_PICKER_END_DIALOG);
		}
	};

	private TimePickerDialog.OnTimeSetListener mTimeSetListener2 = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
			h2 = hourOfDay;
			m2 = minute;

			// generate new reference for today
			Singleton.generateNewReference(m1, h1, m2, h2);

			/*
			 * if (Singleton.currentProject.projectStatus !=
			 * ObsvProject.ProjectStatus.PROJECT_FINISHED){ Intent i = new
			 * Intent(getBaseContext(), NewEmployerActivity.class);
			 * startActivity(i);
			 * 
			 * }
			 */

			if (Singleton.todayReference != null) {
				Log.i("Singleton",
						HardroidUtils
								.dateToSDate(Singleton.todayReference.obsvDate)
								+ "");
			}

			Singleton.saveProject(Singleton.currentProject);
		}
	};

	public boolean onCreateOptionsMenu(android.view.Menu menu) {
		getMenuInflater().inflate(R.menu.dashboard_menu, menu);
		getActionBar().setDisplayHomeAsUpEnabled(true);

		return super.onCreateOptionsMenu(menu);
	};

	private void copyFile(InputStream in, OutputStream out) throws IOException {
		byte[] buffer = new byte[1024];
		int read;
		while ((read = in.read(buffer)) != -1) {
			out.write(buffer, 0, read);
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.menu_dashboard_tentang_work_sampling: {
//			Intent i = new Intent(getContext(), HelpActivity.class);
//			startActivity(i);
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File file = new File(Environment.getExternalStorageDirectory()
						+ "/hardroid/worksampling.pdf");
				if (!file.exists()) {
					InputStream stream;
					try {
						stream = getAssets().open("worksampling.pdf");
						if (stream != null) {

							try {
								OutputStream out = null;
								File fileDir = new File(
										Environment
												.getExternalStorageDirectory(),
										"hardroid");
								fileDir.mkdirs();
								File helpFile = new File(fileDir + "/worksampling.pdf");
								if (helpFile.createNewFile()) {
									out = new FileOutputStream(
											Environment
													.getExternalStorageDirectory()
													+ "/hardroid/worksampling.pdf");
									copyFile(stream, out);
									stream.close();
									stream = null;
									out.flush();
									out.close();

									try {
										Uri path = Uri.fromFile(helpFile);
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										intent.setDataAndType(path,
												"application/pdf");
										intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(intent);

									} catch (Exception e) {
										Toast.makeText(
												getBaseContext(),
												"Tidak ada PDF reader yang ditemukan",
												Toast.LENGTH_SHORT).show();
									}
								} else {
									Toast.makeText(getBaseContext(),
											"Gagal mengcopy file help",
											Toast.LENGTH_SHORT).show();
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				} else {
					try {
						Uri path = Uri.fromFile(new File(Environment
								.getExternalStorageDirectory()
								+ "/hardroid/worksampling.pdf"));
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(path, "application/pdf");
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);

					} catch (Exception e) {
						Toast.makeText(getBaseContext(),
								"Tidak ada PDF reader yang ditemukan",
								Toast.LENGTH_SHORT).show();
					}
				}

			} else {
				Toast.makeText(getBaseContext(),
						"Tidak ada SD card yang ditemukan", Toast.LENGTH_SHORT)
						.show();
			}

			break;
		}
		case R.id.menu_dashboard_help: {
			if (Environment.getExternalStorageState().equals(
					Environment.MEDIA_MOUNTED)) {
				File file = new File(Environment.getExternalStorageDirectory()
						+ "/hardroid/help.pdf");
				if (!file.exists()) {
					InputStream stream;
					try {
						stream = getAssets().open("help.pdf");
						if (stream != null) {

							try {
								OutputStream out = null;
								File fileDir = new File(
										Environment
												.getExternalStorageDirectory(),
										"hardroid");
								fileDir.mkdirs();
								File helpFile = new File(fileDir + "/help.pdf");
								if (helpFile.createNewFile()) {
									out = new FileOutputStream(
											Environment
													.getExternalStorageDirectory()
													+ "/hardroid/help.pdf");
									copyFile(stream, out);
									stream.close();
									stream = null;
									out.flush();
									out.close();

									try {
										Uri path = Uri.fromFile(helpFile);
										Intent intent = new Intent(
												Intent.ACTION_VIEW);
										intent.setDataAndType(path,
												"application/pdf");
										intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
										startActivity(intent);

									} catch (Exception e) {
										Toast.makeText(
												getBaseContext(),
												"Tidak ada PDF reader yang ditemukan",
												Toast.LENGTH_SHORT).show();
									}
								} else {
									Toast.makeText(getBaseContext(),
											"Gagal mengcopy file help",
											Toast.LENGTH_SHORT).show();
								}
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						}

					} catch (IOException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				} else {
					try {
						Uri path = Uri.fromFile(new File(Environment
								.getExternalStorageDirectory()
								+ "/hardroid/help.pdf"));
						Intent intent = new Intent(Intent.ACTION_VIEW);
						intent.setDataAndType(path, "application/pdf");
						intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
						startActivity(intent);

					} catch (Exception e) {
						Toast.makeText(getBaseContext(),
								"Tidak ada PDF reader yang ditemukan",
								Toast.LENGTH_SHORT).show();
					}
				}

			} else {
				Toast.makeText(getBaseContext(),
						"Tidak ada SD card yang ditemukan", Toast.LENGTH_SHORT)
						.show();
			}

			break;
		}
		case R.id.menu_dashboard_about: {
			Intent i = new Intent(getContext(), AboutActivity.class);
			startActivity(i);
			break;
		}
		}
		return super.onOptionsItemSelected(item);
	}

}